<?php
require_once 'Zend/Db.php';
require_once 'Zend/Db/Table.php';


class Model_Expr extends Zend_Db_Expr{
	function __constructor(){
		parent::__constructor();
	}
}

class App_Model extends Zend_Db_Table{
	function __constructor(){
		parent::__constructor();		
	}

	public function query( $statement ){
		return $this->_db->query( $statement );			
	}

	public function exec( $statement ){
		return $this->query( $statement );			
	}
	
	public function lastId(){
		return  $this->_db->lastInsertId();
	}
	
	public function fetchAll( $statement ){
		if( func_num_args() > 1 ){

			$sql = func_get_arg(1);
			$cache_id = 'cache/DB_'.func_get_arg(0);
			
			if ( file_exists( $cache_id ) ){
				return unserialize(file_get_contents($cache_id));				
			}else{ 
				$result = $this->_db->fetchAll( $sql );
				try{
					$f = fopen($cache_id,'w');
					fputs($f, serialize($result));
					fclose($f);
				}catch(Exception $ex ){}	
				return $result;
			}			
			
		}else{
			return $this->_db->fetchAll( func_get_arg(0) );			
		}
	}

	public function fetchRow(){
		if( func_num_args() > 1 ){

			$sql = func_get_arg(1);
			$cache_id = 'cache/DB_'.func_get_arg(0);
			
			if ( file_exists( $cache_id ) ){
				return unserialize(file_get_contents($cache_id));				
			}else{ 
				$result = $this->_db->fetchRow( $sql );
				try{
					$f = fopen($cache_id,'w');
					fputs($f,serialize($result));
					fclose($f);
				}catch(Exception $ex ){}	
				return $result;
			}			
			
		}else{
			return $this->_db->fetchRow( func_get_arg(0) );			
		}	
	}
	
	public function fetchOne(){
		$params = func_get_args();
		
		$result = call_user_func_array(array(&$this,'fetchRow'), $params  );
		
		if( !is_array($result) ){
			return NULL;
		}else{
			foreach( $result as $v )
				return $v;
			return NULL;	
		}		
	}	
	
	public function getTotal( $tb, $where='' ){
		if( $where!='' ){
			$where = " WHERE $where";
		}
		$total = $this->_db->fetchRow("SELECT COUNT(*) AS `total` FROM $tb $where");
		return $total['total'];
	}
	
	public function insert( $tb, $data ){
		return $this->_db->insert($tb,$data );			
	}

	public function update( $tb, $data, $where='' ){
		return $this->_db->update($tb, $data, $where );
	}
	
	public function delete( $tb,$where ){
		return $this->_db->delete( $tb, $where );
	}
	
	public function removeCache($namespace){
		//if $namespace match name*
		// then remove all file match name*	
		$path = "cache/";
		if($m = preg_match('#([^*]+)\*#is', $namespace) ){
		   foreach(scandir($path) as $file) {
				if(is_file($path . $file)) {
					if( substr($file,0,strlen($m[1])) == $m[1] ){
						@unlink($path.'DB_'.$file);
					}	
				}
			}			
		}else{
			@unlink($path.'DB_'.$namespace);			
		}	
	}
	
}
?>
